<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "uploader",
});
</script>
<script lang="ts" setup>
import { ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
const props = defineProps({
  value: {
    required: true,
  },
  action: {
    default: "/api/upload",
  },
});
const emits = defineEmits(["update:value"]);
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const imgsValue = ref<string[]>([]);
const handleRemove: UploadProps["onRemove"] = () => {
  imgsValue.value = fileList.value.map((item) => {
    return item.url as string;
  });
  emits("update:value", imgsValue.value);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

fileList.value = Array.isArray(props.value)
  ? props.value.map((i) => ({ name: i, url: i }))
  : props.value
  ? [{ name: props.value, url: props.value }]
  : [];
const isOne = !Array.isArray(props.value);
const handleSuccess = (uploadFile: any) => {
  if (isOne) {
    if (fileList.value.length > 1) {
      fileList.value.shift();
    }
    emits("update:value", uploadFile);
  } else {
    fileList.value.pop();
    fileList.value.push({ name: uploadFile, url: uploadFile });
    imgsValue.value = fileList.value.map((item) => {
      return item.url as string;
    });
    emits("update:value", imgsValue.value);
  }
};
</script>

<template>
  <div>
    <el-upload
      v-model:file-list="fileList"
      :action="action"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
